package com.kunchi.platform.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kunchi.platform.entity.gateway.CompanyGateway;
import com.kunchi.platform.model.gateway.Gateway;
import com.kunchi.platform.repository.CompanyGatewayRepository;
import com.kunchi.platform.service.GatewayService;
import com.kunchi.platform.service.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;

/**
 * Created by denniszhou on 2017/7/23.
 */
@Service("gatewayService")
public class GatewayServiceImpl implements GatewayService {

  @Value("${baseUrl}")
  private String baseUrl;

  @Value("${login.hash}")
  private String loginHash;

  @Autowired
  RestTemplate restTemplate;

  @Autowired
  LoginService loginService;

  @Autowired
  CompanyGatewayRepository companyGatewayRepository;

  @Override
  public List<Gateway> getGateWayList() throws IOException {
    String url = baseUrl + "/agentList?token={0}";
    String token = loginService.rentLogin();
    String response = restTemplate.getForObject(MessageFormat.format(url, token), String.class);
    String gateways = JSONObject.parseObject(response).getString("data");
    return JSON.parseArray(gateways, Gateway.class);
  }

  @Override
  public CompanyGateway add(CompanyGateway companyGateway) {
    CompanyGateway existed = companyGatewayRepository.findByCompanyIdAndSerialNumber(
        companyGateway.getCompanyId(), companyGateway.getSerialNumber()
    );
    return existed == null ? companyGatewayRepository.save(companyGateway) : existed;
  }

  @Override
  public CompanyGateway delete(CompanyGateway companyGateway) {
    CompanyGateway existed = companyGatewayRepository.findByCompanyIdAndSerialNumber(
        companyGateway.getCompanyId(), companyGateway.getSerialNumber()
    );
    companyGatewayRepository.delete(existed.getId());
    return companyGateway;
  }

  @Override
  public List<CompanyGateway> findByCompanyId(Long companyId) {
    return companyGatewayRepository.findByCompanyId(companyId);
  }
}
